#include "ArmyState.h"
#include "UserAPI.h"
#include "BasicAI.h"
#include "params.h"

using namespace ArmyStateNS;

#define complete() { enter_state(m_name, this, m_parent); return; }

void TemporalAttackingState::execute()
{
	//for (TemporalAttackingState *x = this; x != NULL; )
	//{
	//	LOG << x->get_type() << '->';
	//	if (x->m_parent->get_type() == "TemporalAttackingState")
	//		x = (TemporalAttackingState*)x->m_parent;
	//	else
	//	{
	//		LOG << x->m_parent->get_type() << '->';
	//		break;
	//	}
	//}
	if (executed)
		complete();

	BasicAI *ai = BasicAI::instance();
	UserAPI &api = ai->get_api();
	Army *army = api.GetCntArmy();
	//	TODO	change to useful state?

	executed = true;

	if (m_type == ATTACKING_GENERAL)
	{
		Army *enemy = api.GetArmy(target_general_name);
		vector<Army*> op_troop_around = api.GetOpArmyAround(army->pos, 8);

		if (enemy && api.HamDistance(enemy->pos,  army->pos) <= 8)
		{
			api.AttackArmy(ai->get_action_queue(), army->pos, enemy);
			return;
		} else if (op_troop_around.size() > 0)
		{
			enemy = api.GetNearestArmy(army->pos, op_troop_around);
			api.AttackArmy(ai->get_action_queue(), army->pos, enemy);
			return;
		} else if (enemy)
		{
			api.AttackArmy(ai->get_action_queue(), army->pos, enemy);
			return;
		} else
		{
			complete();
			return;
		}	
	} else
	{
		executed = true;
		LOG_ASSERT(m_type == ATTACKING_CITY, "what's your type, no city no general?");
		LandCity *city = api.GetCity(target_city_pos);
		if (city->owner == api.get_my_id())
			complete();

		if (city->HP > 0)
		{
			api.AttackCity(ai->get_action_queue(), army->pos, city);
			return;
		} else
		{
			api.Move(ai->get_action_queue(), army->pos, api.GetCityCenter(city));
			return;
		}
	}
}